<!--suppress ALL -->
<!DOCTYPE html>
<!-- 其余原有代码 -->
<div id="dataFormDiv"></div>
<script type="text/html" id="dataFormContent">
  <form lay-filter="returnRecordsDataForm" class="layui-form model-form" id="returnRecordsDataForm">
    <div class="open-model">
      <div class="open-auto">
        <input name="id" type="hidden" />
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">{{d.typeNameData}}类型</label>
            <div class="layui-input-inline">
              <select id="type" name="type" lay-filter="type"></select>
            </div>
          </div>
        </div>
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">订单类型</label>
            <div class="layui-input-inline">
              <select id="typeCode" name="typeCode" lay-filter="typeCode"></select>
            </div>
          </div>
        </div>
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">运单编号</label>
            <div class="layui-input-inline">
              <select id="waybillNo" name="waybillNo" lay-filter="waybillNo"></select>
              <!-- <input type="hidden" name="orderId"/> -->
            </div>
          </div>
        </div>
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">关联订单编号</label>
            <div class="layui-input-inline">
              <input id="orderCode" class="layui-input" type="text" name="orderCode" disabled />
              <input type="hidden" name="orderId" />
            </div>
          </div>
        </div>
        <!-- 写一个row换行 -->
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-inline">
              <input class="layui-input" disabled name="supplierName" />
              <input class="layui-input" type="hidden" name="supplierId" />
            </div>
          </div>
        </div>

        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">{{d.typeNameData}}备注</label>
            <div class="layui-input-inline">
              <input name="remark" id="remark" class="layui-input" type="text" />
            </div>
          </div>
        </div>
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label w-120">物料图片</label>
            <div class="layui-input-inline">
              <div id="productPicBtn1" class="layui-btn" style="float: left;">
                <i class="layui-icon">&#xe681;</i>
                上传图片
              </div>
              <input name="fileUrl" type="hidden" class="layui-input" lay-verify="" id="fileUrl" />
              <input name="fileName" type="hidden" class="layui-input" lay-verify="" id="fileName" />
              <img id="ImgDIv" style="margin-top: 10px;width: 150px;height: 100px;display: none;" />
            </div>
          </div>
        </div>

        <table class="layui-table" lay-filter="returnRecordsDataTable" id="returnRecordsDataTable"></table>
      </div>
    </div>
  </form>
</script>

<script>
  layui.use(['layer', 'form', 'table', 'admin', 'upload', 'tree', 'laytpl'], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    var laytpl = layui.laytpl;
    const nowData = { ...parentData };
    console.log(nowData);
    // const parentData=JSON.parse(JSON.stringify(parentData.data))
    data = nowData.data;
    // form.render('select')
    laytpl(dataFormContent.innerHTML).render({ ...nowData }, function (html) {
      $('#dataFormDiv').html(html);
    });
    admin.setFormDisable('#returnRecordsDataForm', true);
    // 表单禁用
    //    if (['detail'].includes(nowData.eventName)) {
    //        admin.setFormDisable('#returnRecordsDataForm', true)
    //    }
    await admin.initDataSelectPro(
      'enterprisecab/warehouse/admin/warehouseInventoryType/list',
      { inventoryType: 'out', supportReturn: 1, limit: 9999, status: 'enable' },
      'typeCode',
      '订单类型',
      async (d, obj) => {
        form.val('returnRecordsDataForm', {
          supplierName: '',
          supplierId: '',
          orderCode: '',
          orderId: '',
        });
        table.reload('returnRecordsDataTable', { data: [] });
        $('#waybillNo').empty();
        if (d.value) {
          await admin.initDataSelectPro(
            'enterprise/sell/admin/deliveryRecord/list',
            { limit: 9999, typeCode: d.value },
            'waybillNo',
            '运单编号',
            (d, obj) => {
              form.val('returnRecordsDataForm', {
                supplierName: '',
                supplierId: '',
                orderCode: '',
                orderId: '',
              });
              if (d.value) {
                form.val('returnRecordsDataForm', {
                  supplierName: obj.customerName,
                  supplierId: obj.customerId,
                  orderCode: obj.saleOrderCode,
                  orderId: obj.saleOrderId,
                });
              }
            },
            'recordCode',
          );
        }
      },
      'name',
      'code',
    );
    await admin.initDataSelectPro('enterprise/sell/admin/customerReturnType/list', {}, 'type', `${nowData.typeNameData}类型`);
    const return_methodRes = await admin.getDictListPro('returnType', 'return_method', `发货方式`);

    table.render({
      elem: '#returnRecordsDataTable',
      data: [],
      page: false,
      cols: [
        [
          {
            tyoe: 'numbers',
            title: '序号',
          },
          {
            field: 'logisticsWaybillNo',
            title: '物流单号',
          },
          {
            field: 'returnType',
            title: '发货方式',
            templet: admin.setTableSelect(
              'returnType',
              return_methodRes.map((v) => {
                return {
                  label: v.labelName,
                  value: v.labelValue,
                };
              }),
              true,
            ),
          },
          {
            field: 'logisticsCompany',
            title: '物流公司',
          },
          {
            field: 'busNumber',
            title: '车牌号',
          },
          {
            field: 'busNumber',
            title: '收货数量',
          },
          {
            align: 'center',
            title: '操作',
            fixed: 'right',
            templet: `<div>
                    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="edit">详情</a>
                    </div>`,
          },
        ],
      ],
    });
    if (data && data.id) {
      if (data.typeCode) {
        await admin.initDataSelectPro('enterprise/sell/admin/deliveryRecord/list', { limit: 9999, typeCode: data.typeCode }, 'waybillNo', '运单编号', null, 'recordCode');
      }
      form.val('returnRecordsDataForm', data);

      // if (nowData.typeNameData === '退货') {
      //   console.log('nowData.eventName', nowData.eventName);

      //   if (nowData.eventName === 'getDataHis') {
      //     table.reload('returnRecordsDataTable', {
      //       data: data.getSelGoodsLogisticsDetails,
      //     });
      //   }
      // } else {
      if (nowData.eventName === 'getDataHis') {
        table.reload('returnRecordsDataTable', {
          data: data.getSelGoodsLogisticsDetails,
        });
      } else {
        table.reload('returnRecordsDataTable', {
          data: data.sendSelGoodsLogisticsDetails,
        });
      }
      // }
    }
    function submitFormData(url, data, method) {
      admin.req(
        url,
        JSON.stringify(data),
        function (res) {
          if (res.code == 200) {
            layer.msg('操作成功');
            table.reload('returnRecordsTable');
            layer.closeAll();
          } else {
            layer.msg(res.msg);
          }
        },
        method,
        true,
        'application/json; charset=utf-8',
      );
    }
    // 表单提交事件
    form.on('submit(productDetailSubmit)', function (d) {
      let formData = { ...d.field };
      if (nowData.typeNameData === '退货') {
        formData.selReturnGoodsRecordsDetails = table.cache['returnRecordsDataTable'];
        formData.moduleType = 1;
      } else {
        formData.selReturnGoodsRecordsDetails = table.cache['returnRecordsDataTable'];
        formData.moduleType = 2;
      }

      if (nowData.eventName === 'add') {
        submitFormData(nowData.addUrl, formData, 'POST');
      } else if (nowData.eventName === 'edit') {
        submitFormData(nowData.addUrl, formData, 'PUT');
      } else if (nowData.eventName === 'getData') {
        formData.goodType = '1';
        formData.waybillNo = formData.danHao;
        formData.recordId = formData.id;
        formData.details = table.cache['returnRecordsDataTable'].map((v) => {
          v.recordDetailId = v.id;
          return v;
        });
        submitFormData(nowData.addLogisticsInfo, formData, 'POST');
      }
      return false;
    });

    imgUpload();
    table.on('tool(returnRecordsDataTable)', function (obj) {
      var data = obj.data;
      let dataList = [];
      if (nowData.eventName === 'setDataHis') {
        dataList = nowData.data.sendSelGoodsLogisticsDetails.find((v) => v.id == data.id).selGoodsLogisticsDetails;
      } else {
        dataList = nowData.data.getSelGoodsLogisticsDetails.find((v) => v.id == data.id).selGoodsLogisticsDetails;
      }
      admin.formOpen({
        title: `查看${nowData.typeNameData}记录详情`,
        area: ['70%', '40%'],
        content: '<table id="returnRecordsFormTable" lay-filter="returnRecordsFormTable"></table>',
        success: function () {
          table.render({
            elem: '#returnRecordsFormTable',
            data: dataList,
            cols: [
              [
                {
                  field: 'skuCode',
                  title: '产品编号',
                },
                {
                  field: 'skuSpec',
                  title: '规格码',
                },
                {
                  field: 'skuName',
                  title: '产品名称',
                },
                {
                  field: 'mainUnitName',
                  title: '主计价单位',
                },
                {
                  title: '收货数量',
                  templet: function (d) {
                    return d.realGetQuantity ? d.realGetQuantity : d.realSendQuantity;
                  },
                },
                {
                  field: 'unitPrice',
                  title: '单价',
                },
                {
                  field: 'totalPrice',
                  title: '总价',
                },
              ],
            ],
          });
        },
      });
    });
    function imgUpload() {
      upload.render({
        elem: '#productPicBtn1',
        url: config.upload_url + 'uploadFile',
        accept: 'file',
        headers: {
          Authorization: 'Bearer ' + config.getToken(),
        },
        // acceptMime: 'image/*',
        exts: 'jpg|jpeg|png|gif',
        done: function (res) {
          // On successful upload
          if (res.code === 200) {
            $('#fileUrl').val(res.data.url); // Store the image URL in hidden input
            $('#fileName').val(res.data.fileName); // Store the image URL in hidden input
            $('#ImgDIv').attr('src', res.data.url).show(); // Show image preview
            $('#ImgDIv').attr('style', 'margin-top: 10px;width: 150px;height: 100px;display: block;');
            layer.msg('图片上传成功');
          } else {
            layer.msg('图片上传失败: ' + res.msg);
          }
        },
        error: function () {
          // On upload failure
          layer.msg('上传失败，请重试');
        },
      });
    }
  });
</script>

<style>
  .layui-form-label {
    width: 100px;
  }
</style>
